// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()
const $ = db.command.aggregate
const _ = db.command

// 云函数入口函数
exports.main = async (event, context) => {
  var userInfo = []
  var data = await cloud.database().collection('discuss-post').aggregate()
    .match({
      _id: event.id
    })
    .project({
      _id: 1,
      _openid: 1,
      _createTime: 1,
      comments: 1,
      views: 1,
      content: 1,
      pic: 1
    })
    .lookup({
      from: 'discuss-comment',
      localField: '_id',
      foreignField: 'postId',
      as: 'comment'
    })
    .lookup({
      from: 'user',
      localField: '_openid',
      foreignField: '_id',
      as: 'poster'
    })
    .end()
  data.list[0].comment.reverse()
  for (var i in data.list[0].comment) {
    await cloud.database().collection('user')
      .doc(data.list[0].comment[i]._openid)
      .get()
      .then(res => {
        data.list[0].comment[i]['userInfo'] = res.data.userInfo
      })
  }

  return userInfo.concat(data.list[0])
}